package org.mech.sefer.client.app;

import java.util.ArrayList;
import java.util.List;

import org.apache.pivot.collections.Map;
import org.apache.pivot.wtk.Application;
import org.apache.pivot.wtk.Display;
import org.apache.pivot.wtk.FillPane;
import org.apache.pivot.wtk.Window;
import org.mech.sefer.client.app.spring.SpringLoader;
import org.mech.sefer.client.ui.component.layout.main.MainPresenter;
import org.mech.sefer.client.ui.component.layout.main.MainView;
import org.mech.sefer.client.ui.event.BibleEvents;
import org.mech.sefer.event.bus.EventBus;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SeferClient extends Application.Adapter implements
		ApplicationContextAware {

	private List<Lifecycle> lifecycles = new ArrayList<Lifecycle>();

	private ApplicationContext context;

	public SeferClient() {
		lifecycles.add(new SpringLoader());
	}

	@Override
	public boolean shutdown(boolean arg0) throws Exception {
		for (Lifecycle lifecycle : lifecycles) {
			lifecycle.onShutdown(this);
		}
		return false;
	}

	@Override
	public void startup(Display display, Map<String, String> map)
			throws Exception {
		try {
			for (Lifecycle lifecycle : lifecycles) {
				lifecycle.onStart(this);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		EventBus bus = (EventBus) context.getBean("eventBus");

//		BibleTreePresenter presenter = (BibleTreePresenter) context
//				.getBean("bibleTreePresenter");
		
		MainPresenter presenter = context.getBean("mainPresenter", MainPresenter.class);

		Window window = new Window();
		
		((MainView)presenter.getView()).setOwner(window);
		
		FillPane fillPane = new FillPane();
		fillPane.add(presenter.getView().asComponent());

		window.setContent(fillPane);
		window.setTitle("Hello World!");
		window.setMaximized(true);

		window.open(display);
		

		bus.fireEvent(new BibleEvents.BibleRequestEvent());
	}

	public void registerLifecycle(Lifecycle lifecycle) {
		lifecycles.add(lifecycle);
	}

	public void unregisterLifecycle(Lifecycle lifecycle) {
		lifecycles.remove(lifecycle);
	}

	@Override
	public void setApplicationContext(ApplicationContext aContext)
			throws BeansException {
		this.context = aContext;
	}

}
